package gormx

import (
	"fmt"
	"strings"
	"time"

	"gorm.io/gorm"
)

func TableSubffix(tableName, subffix string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		tableName = tableName + subffix
		return db.Table(tableName)
	}
}

func Table(tableName string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Table(tableName)
	}
}

// 获取当前月的表名 baseTableName_yearmonth
func GetMonthTableName(baseTableName string) string {
	baseTableName = removeTableQuota(baseTableName)
	n := time.Now()
	year := n.Year()
	month := n.Month()
	return GetMonthTableNameWithYearAndMonth(baseTableName, year, int(month))
}

// 获取当前年的表名 baseTableName_year
func GetYearTableName(baseTableName string) string {
	baseTableName = removeTableQuota(baseTableName)
	n := time.Now()
	year := n.Year()
	return GetYearTableNameWithYear(baseTableName, year)
}

// 获取指定年月的表名 baseTableName_yearmonth
func GetMonthTableNameWithYearAndMonth(baseTableName string, year int, month int) string {
	baseTableName = removeTableQuota(baseTableName)
	return fmt.Sprintf("%s_%d%d", baseTableName, year, month)
}

// 获取指定年的表名 baseTableName_year
func GetYearTableNameWithYear(baseTableName string, year int) string {
	baseTableName = removeTableQuota(baseTableName)
	return fmt.Sprintf("%s_%d", baseTableName, year)
}

func removeTableQuota(baseTableName string) string {
	return strings.Trim(baseTableName, "`")
}
